package com.smartum.mpr.utils;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.log4j.Logger;

public class ZipUtil {

	public static void unzip(String zipFile, String outputFolder) {

		ZipInputStream zis = null;
		try {
			zis = new ZipInputStream(new FileInputStream(zipFile));
			unzip(zis, outputFolder);
			zis.closeEntry();
			zis.close();

		} catch (IOException ex) {
			Logger.getLogger(ZipUtil.class).error("can't unzip file");
		} finally {
			closeStream(zis);
		}
	}

	public static List<String> unzip(InputStream zipIS, String outputFolder) {

		byte[] buffer = new byte[1024];
		ZipInputStream zis = null;
		List<String> fileNames = new ArrayList<String>();
		try {

			File folder = new File(outputFolder);
			if (!folder.exists()) {
				folder.mkdir();
			}

			zis = new ZipInputStream(zipIS);
			ZipEntry ze = zis.getNextEntry();

			while (ze != null) {
				String fileName = ze.getName();
				fileNames.add(fileName);
				File newFile = new File(outputFolder + File.separator + fileName);
				new File(newFile.getParent()).mkdirs();
				FileOutputStream fos = new FileOutputStream(newFile);
				int len;
				while ((len = zis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}

				fos.close();
				ze = zis.getNextEntry();
			}

			zis.closeEntry();
			zis.close();

		} catch (IOException ex) {
			Logger.getLogger(ZipUtil.class).error("can't unzip file");
		} finally {
			closeStream(zis);
		}
		return fileNames;
	}

	public static void closeStream(Closeable stream) {
		try {
			if (stream != null)
				stream.close();
		} catch (Exception e) {
		}
	}

}
